//
//  FeedbackVC.swift
//  Hyphenate-Demo-Swift
//
//  Created by cydida on 2018/12/8.
//  Copyright © 2018年 curtainups. All rights reserved.
//

import UIKit
import Hyphenate
//import Toast_Swift
import Alamofire
import Photos

class FeedbackVC: UIViewController {

    @IBOutlet weak var imgBtn: UIButton!
    
    @IBOutlet weak var textView: EMMessageTextView!
    
    var imageLocalPath = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textView.set(placeHolder: "input your feedback".localized() as NSString)
        
        let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                           .userDomainMask, true)[0] as String
        imageLocalPath = "\(rootPath)/feedback.jpg"
        // Do any additional setup after loading the view.
    }
    
    @IBAction func commitActon(_ sender: Any) {
        
        
        if(textView.text == ""){
            
            self.showAlert("input your feedback".localized())
            return;
        }
        
        feedBackAction()
    }
    
    @IBAction func imgBtnAction(_ sender: Any) {
        
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        self.present(imagePickerController, animated: true, completion: nil)
    }
    //    //上传图片
    func feedBackAction() {
        
        
        weak var weakSelf = self;
        
        let image =  UIImage(contentsOfFile: imageLocalPath)
        var imgData:Data? = nil
        
        if(image != nil)
        {
            imgData = UIImageJPEGRepresentation(image!, 0.2)!
        }
        
        let parameters = ["username": EMClient.shared().currentUsername,
                          "text":textView.text]
        
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            
            if image != nil{
                multipartFormData.append(imgData!, withName: "image", fileName: "user_profiel_image.jpeg", mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append((value?.data(using: String.Encoding.utf8))!, withName: key)
            }
        }, to: CUHTTP.URL.ROOT + "feedback")
        { (result) in
            switch result {
            case .success(let upload, _, _):
                
                upload.uploadProgress(closure: { (progress) in
                    //Print progress
                })
                
                upload.responseString { response in
                    print(response.result)
                    if response.result.isSuccess
                    {
                        weakSelf?.show("succeed".localized())
                        weakSelf?.navigationController?.popViewController(animated: true)
                    }
                }
                
            case .failure(let encodingError): break
            }
        }
    }
}
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */



extension FeedbackVC: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        // Dismiss the picker if the user canceled.
        dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard var selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        
        // Dismiss the picker.
        dismiss(animated: true, completion: nil)
        
        //压缩图片到36k左右
        let img = selectedImage.imageByScalingAndCroppingForSize(targetSize: CGSize.init(width: 160, height: 160))
        selectedImage = img
        
        var KB = 0.0
        if let imageData = UIImagePNGRepresentation(selectedImage) {
            let bytes = imageData.count
            KB = Double(bytes) / (1024.0*1024.0) // Note the difference
        }
        //2M
        if KB >= 2 {
            //图片太大
            self.show(EnStatic.getWord(keyWord: "avatar bigger than 2M"))
            //设置无头像状态
        } else {
            // Set photoImageView to display the selected image.
        
            self.imgBtn.setBackgroundImage(selectedImage, for: UIControlState.normal)
            
            //将选择的图片保存到Document目录下
            let fileManager = FileManager.default
            let imageData = UIImageJPEGRepresentation(selectedImage, 1.0)
            fileManager.createFile(atPath: imageLocalPath, contents: imageData, attributes: nil)
        }
        
    }
}
